<template>
  <div class="fence-create">
    <div class="fence-create__warp">
      <div class="side-bar">
        <div class="side-bar__title">
          围栏列表
        </div>

        <div
          v-loading="fenceListLoading"
          class="side-bar__content"
        >
          <el-scrollbar style="width: 100%;height: 100%;">
            <div
              v-for="(item, index) in fenceList"
              :key="index"
              class="fence-item"
              :class="{
                'fence-item--active': currentFence?.id === item?.id
              }"
              @click="handleCurrentFence(item)"
            >
              <div class="left flex" style="align-items: center;">
                <svg-icon icon-class="fence" />
                <div class="fence-name">
                  <span v-if="!isEditFenceName || currentFence?.id !== item.id">
                    {{ item.title }}
                  </span>
                  <el-input
                    v-if="isEditFenceName && currentFence?.id === item.id"
                    v-model="item.title"
                    size="mini"
                    style="width: 100px;"
                    @blur="updateFenceName(item)"
                  />
                  <i
                    class="edit-icon"
                    :class="{
                      'el-icon-edit-outline': !isEditFenceName || currentFence?.id !== item.id,
                      'el-icon-circle-close': isEditFenceName && currentFence?.id === item.id
                    }"
                    @click.stop="handleEditFenceName(item)"
                  />
                </div>
              </div>

              <div class="right">
                <div
                  class="el-icon-edit"
                  @click.stop="handleEditFence(item)"
                />

                <div
                  class="el-icon-delete"
                  style="margin-left: 10px;"
                  @click.stop="handleRemoveFence(item)"
                />
              </div>
            </div>
          </el-scrollbar>
        </div>

        <div class="side-bar__footer">
          <el-button
            type="text"
            size="mini"
            icon="el-icon-circle-plus"
            @click="handleCreateFence(1)"
          >
            圆形围栏
          </el-button>

          <el-button
            type="text"
            size="mini"
            icon="el-icon-circle-plus"
            @click="handleCreateFence(2)"
          >
            多边形围栏
          </el-button>

          <!--          <el-button-->
          <!--            type="text"-->
          <!--            size="mini"-->
          <!--            icon="el-icon-circle-plus"-->
          <!--            @click="handleCreateFence(3)"-->
          <!--          >-->
          <!--            行政区域-->
          <!--          </el-button>-->
        </div>
      </div>
      <div
        :id="mapRef"
        class="fence-create__warp__map"
      />
    </div>

    <FenceCreateDialog
      :visible.sync="createDialogVisible"
      :title="isEditFence ? '编辑围栏' : '创建围栏'"
      :model="model"
      :fence-type="fenceType"
      :selector-options="selectorOptions"
      :loading="loading"
      :is-edit="isEditFence"
      @confirm="handleFenceCreateConfirm"
      @cancel="handleCreateFenceCancel"
      @radiusChange="handleRadiusChange"
    />
  </div>
</template>
<script>
import TdtPublicMixin from '@/mixins/TdtPublicMixin'
import '@/assets/Tdt/D3SvgOverlay'
import '@/assets/Tdt/CarTrack'
import FenceCreateDialog from '@/views/vehicleService/components/fenceCreate/FenceCreateDialog.vue'
import { getVehiclesList } from '@/api/vehicleService'
import { FenceType } from '@/views/vehicleService/components/fenceCreate'
import { editFenceName, editGpsFence, getFenceList, removeGpsFence, setGpsFence } from '@/api/gps'
import coordtransform from 'coordtransform'
export default {
  name: '',
  components: { FenceCreateDialog },
  mixins: [TdtPublicMixin],
  data() {
    return {
      createDialogVisible: false,
      fenceType: 1,
      model: {
        title: '',
        in_rail_alarm: 0,
        out_rail_alarm: 0,
        imei_list: [],
        circular_lat: null,
        circular_lon: null,
        circular_radius: 200,
        adm_area_code: null,
        rail_info: ''
      },
      vehicleList: [],
      circleMarker: null,
      loading: false,
      fenceList: [],
      fenceListLoading: false,
      currentFence: null,
      isEditFence: false,
      isCreatingCircleFence: false,
      isEditFenceName: false
    }
  },
  computed: {
    selectorOptions() {
      return this.vehicleList.map(item => {
        return {
          label: `${item?.type?.name}-${item?.license_plate_number}`,
          value: item.imei
        }
      }).filter(item => item.value)
    }
  },
  created() {
    this.T = window.T
    this.getVehicleList()
    this.getFenceList()
  },
  mounted() {
    this.init()
    this.addMapMouseDown()
    this.addMapMouseUp()
  },
  beforeDestroy() {
    this.removeMapEvent('click', () => {})
    this.removeMapEvent('mousedown', () => {})
    this.removeMapEvent('mouseup', () => {})
  },
  methods: {
    handleCreateFence(type = 1) {
      this.removeMapEvent('click')
      this.clearMarker()
      this.isCreatingCircleFence = false
      this.currentFence = null
      this.isEditFence = false
      this.model = this.$options.data().model
      this.fenceType = type

      if (this.polygonTool) this.polygonTool.close()

      if (type === FenceType.CIRCLE) {
        this.isCreatingCircleFence = true
        this.handleCreateCircularFence()
      } else if (type === FenceType.POLYGON) {
        this.handleCreatePolygonFence()
      } else if (type === FenceType.ADMINISTRATIVE_REGION) {
        const size = this.map.getSize()
        console.log('size --------->', size)
        this.$message.warning('该功能暂不支持')
        // this.createDialogVisible = true
      }
    },

    handleCreateCircularFence() {
      this.$message.warning('请在地图上选择围栏中心点')
      this.changeMapCursorStyle('crosshair')

      this.addMapEvent('click', (e) => {
        const { lat, lng } = e.lnglat
        this.model.circular_lat = lat
        this.model.circular_lon = lng
        this.addMarker(lng, lat)
        this.changeMapCursorStyle('grab')
        this.circleMarker = this.addCircleToMap(lng, lat, 200)
        this.createDialogVisible = true
        this.isCreatingCircleFence = false
      })
    },

    handleCreatePolygonFence() {
      this.createPolygonTool()
      this.$message.warning('请在地图上选择围栏边界点，请至少选择三个点')
      this.polygonTool.addEventListener('draw', (e) => {
        console.log('e --------->', e)
        this.model.rail_info = e.currentLnglats
        this.createDialogVisible = true
        this.polygonTool.close()
      })
    },

    addMapMouseDown(e) {
      this.addMapEvent('mousedown', () => {
        this.changeMapCursorStyle('grabbing')
      })
    },

    addMapMouseUp(e) {
      this.addMapEvent('mouseup', () => {
        if (this.isCreatingCircleFence) {
          this.changeMapCursorStyle('crosshair')
        } else {
          this.changeMapCursorStyle('grab')
        }
      })
    },

    async getFenceList() {
      this.fenceListLoading = true
      try {
        const res = await getFenceList()
        console.log('res --------->', res)
        this.fenceList = res.data
      } catch (error) {
        this.$message.error('围栏列表获取失败')
      } finally {
        this.fenceListLoading = false
      }
    },

    async getVehicleList() {
      try {
        const res = await getVehiclesList()
        this.vehicleList = res.data
      } catch (error) {
        throw new Error(error.message || '车辆列表获取失败')
      }
    },

    handleFenceCreateConfirm(e) {
      this.removeMapEvent('click')
      this.loading = true

      if (!this.isEditFence) {
        const params = this.paramsFormatter(e)

        this.fenceCreateFetch(params)
      } else {
        const params = {
          ...e,
          imei_list: JSON.stringify(e.imei_list)
        }

        this.fenceEditFetch(params)
      }
    },

    paramsFormatter(params) {
      const circularLat = params.circular_lat
      const circularLon = params.circular_lon

      const data = {
        ...params,
        rail_type: this.fenceType,
        imei_list: JSON.stringify(params.imei_list)
      }

      if (this.fenceType === FenceType.CIRCLE) {
        const [bd09Lng, bd09Lat] = this.wgs84ToBd09(circularLon, circularLat)
        data.circular_lat = bd09Lat
        data.circular_lon = bd09Lng
      }

      if (this.fenceType === FenceType.POLYGON) {
        const railInfo = data.rail_info

        data.rail_info = railInfo.map(item => {
          const [bd09Lng, bd09Lat] = this.wgs84ToBd09(item.lng, item.lat)
          return `${bd09Lat},${bd09Lng}`
        }).join(';')
      }

      return data
    },

    async fenceCreateFetch(data) {
      try {
        const res = await setGpsFence(data)
        this.$message.success('围栏创建成功')
        this.createDialogVisible = false
        await this.getFenceList()
      } catch (error) {
        this.$message.error(error.response.data.message || '创建围栏失败')
      } finally {
        this.loading = false
      }
    },

    async fenceEditFetch(data) {
      try {
        const res = await editGpsFence(data)
        this.$message.success('围栏修改成功')
        this.createDialogVisible = false
        this.isEditFence = false
        await this.getFenceList()
      } catch (error) {
        this.$message.error(error.response.data.message || '创建围栏失败')
      } finally {
        this.loading = false
      }
    },

    handleCreateFenceCancel() {
      this.removeMapEvent('click')
      if (!this.isEditFence) {
        this.clearMarker()
      }
    },

    handleRadiusChange(e) {
      const { circular_lat, circular_lon } = this.model

      if (this.circleMarker) this.removeOverLay(this.circleMarker)

      this.circleMarker = this.addCircleToMap(circular_lon, circular_lat, e)
    },

    handleEditFence(item) {
      this.isEditFence = true
      this.fenceType = item.rail_type
      this.model = {
        id: item.id,
        rail_id: item.rail_id,
        title: item.title,
        imei_list: JSON.parse(item.imei_list),
        in_rail_alarm: item.in_rail_alarm,
        out_rail_alarm: item.out_rail_alarm,
        circular_radius: item.circular_radius ? parseInt(item.circular_radius) : 0
      }
      this.handleCurrentFence(item)

      this.createDialogVisible = true
    },

    handleRemoveFence(item) {
      this.$confirm(
        '是否删除该项？',
        '提示',
        {
          type: 'warning',
          showCancelButton: true,
          showConfirmButton: true,
          cancelButtonText: '取消'
        }
      ).then(() => {
        this.removeFenceFetch({ id: item.id, rail_id: item.rail_id })
      })
    },

    async removeFenceFetch(params) {
      try {
        const res = await removeGpsFence(params.id, { rail_id: params.rail_id })
        this.$message.success('删除成功')
        this.clearMarker()
        await this.getFenceList()
      } catch (error) {
        this.$message.error(error.response?.data?.message || '删除失败')
      }
    },

    handleCurrentFence(item) {
      this.currentFence = item
      this.clearMarker()

      if (item.rail_type === FenceType.CIRCLE) {
        const { circular_lat, circular_lon } = item
        const [lon, lat] = this.bd09ToWgs84(circular_lon, circular_lat)
        this.addMarker(lon, lat)
        this.circleMarker = this.addCircleToMap(lon, lat, parseInt(item.circular_radius))
        const bounds = this.circleMarker.getBounds()
        this.fitToOverlay([bounds.Lq, bounds.kq])
      } else if (item.rail_type === FenceType.POLYGON && !item.adm_area_code) {
        const railInfo = item.rail_info.split(';').map(item => {
          const [lat, lon] = item.split(',')
          const [finalLon, finalLat] = this.bd09ToWgs84(lon, lat)

          return this.initialLngLat(finalLon, finalLat)
        })

        const polygon = this.addPolygonToMap(railInfo)
        this.fitToOverlay(railInfo)
      }
    },

    wgs84ToBd09(lon, lat) {
      const [gcj02Lng, gcj021Lat] = coordtransform.wgs84togcj02(lon, lat)
      const [bd09Lng, bd09Lat] = coordtransform.gcj02tobd09(gcj02Lng, gcj021Lat)

      return [bd09Lng, bd09Lat]
    },

    bd09ToWgs84(lon, lat) {
      const [gcj02Lng, gcj021Lat] = coordtransform.bd09togcj02(lon, lat)
      const [wgs84Lng, wgs84Lat] = coordtransform.gcj02towgs84(gcj02Lng, gcj021Lat)

      return [wgs84Lng, wgs84Lat]
    },

    handleEditFenceName(item) {
      this.isEditFenceName = !this.isEditFenceName
      if (this.isEditFenceName) {
        this.handleCurrentFence(item)
      }
    },

    updateFenceName(item) {
      console.log('item --------->', item)
      this.isEditFenceName = false
      const data = {
        id: item.id,
        title: item.title,
        rail_id: item.rail_id
      }

      this.fenceNameUpdateFetch(data)
    },

    async fenceNameUpdateFetch(data) {
      try {
        const res = await editFenceName(data)
        this.$message.success('修改围栏名称成功')
      } catch (error) {
        this.$message.error(error.response.data.message || '修改围栏名称失败')
      }
    }

  }
}
</script>

<style>
.tdt-control-copyright {
  display: none !important;
}
.tdt-control-datasources {
  display: none !important;
}
</style>

<style lang="scss" scoped>
.fence-create  {
  width: 100%;
  height: 90vh;

  &__warp {
    width: 100%;
    height: 100%;
    display: flex;

    .side-bar {
      width: 17%;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      &__title {
        padding: 10px;
        font-size: 18px;
        font-weight: 600;
        border-bottom: 1px solid #F5F5F5;
      }

      &__content {
        flex: 1;
        overflow-y: auto;
        padding: 10px;

        .fence-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px;
          border-radius: 5px;
          cursor: pointer;
          transition: all .3s;
          font-size: 14px;
          margin-bottom: 10px;
          background-color: #F5F7FA;
          border: 1px solid #F5F7FA;

          .edit-icon {
            display: none;
            margin-left: 5px;
          }

          &:last-child {
            margin-bottom: 0;
          }

          &:hover {
            border: 1px solid #409EFF;

            .edit-icon {
              display: inline-block;
            }
          }

          &--active {
            border: 1px solid #409EFF;
          }

          .fence-name {
            margin-left: 10px;
          }
        }
      }

      &__footer {
        padding: 10px;
        border-top: 1px solid #F5F5F5;
      }
    }

    &__map {
      width: 83%;
      height: 100%;
    }
  }
}

::v-deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}
</style>
